package com.example.wastewater.common.biz.user;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.example.wastewater.common.convention.exception.ClientException;
import com.example.wastewater.common.convention.result.Results;
import com.example.wastewater.dao.entity.UserDO;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import static com.example.wastewater.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.example.wastewater.common.enums.UserErrorCode.USER_TOKEN_FAIL;

/**
 * 用户信息传输过滤器
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter{

    private final StringRedisTemplate stringRedisTemplate;

    private static final List<String> IGNORE_URI = List.of(
            "/api/waste-water/admin/v1/user/register",
            "/api/waste-water/admin/v1/user/login",
            "/api/waste-water/admin/v1/send-email",
            "/api/waste-water/admin/v1/log-add",
            "/api/waste-water/admin/v1/water-data-no-BOD"
    );

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = getHttpServletResponse((HttpServletResponse) servletResponse);

        // 确保OPTIONS请求不被过滤器阻挡
        if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        // 设置CSP头
        httpServletResponse.setHeader("Content-Security-Policy", "default-src 'self'; connect-src 'self' http://8.130.112.136:8080");

        String requestURI = httpServletRequest.getRequestURI();
        if (!IGNORE_URI.contains(requestURI)) {
            String email = httpServletRequest.getHeader("email");
            String token = httpServletRequest.getHeader("token");
            if (!StrUtil.isAllNotBlank(email, token)) {
                returnJson(httpServletResponse, JSONUtil.toJsonStr(Results.failure(new ClientException(USER_TOKEN_FAIL))));
                return;
            }
            Object userInfoJsonStr;
            try {
                userInfoJsonStr = stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + email, token);
                if (userInfoJsonStr == null) {
                    throw new ClientException(USER_TOKEN_FAIL);
                }
            } catch (Exception ex) {
                returnJson(httpServletResponse, JSONUtil.toJsonStr(Results.failure(new ClientException(USER_TOKEN_FAIL))));
                return;
            }
            UserDO userInfoDTO = JSON.parseObject(userInfoJsonStr.toString(), UserDO.class);
            UserContext.setUser(userInfoDTO);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }

    private static HttpServletResponse getHttpServletResponse(HttpServletResponse servletResponse) {
        HttpServletResponse httpServletResponse = servletResponse;

        // 添加CORS头
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:5173");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, token, email");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");

        httpServletResponse.setHeader("Content-Security-Policy", "default-src 'self'; connect-src 'self' http://8.130.112.136:8080");
        return httpServletResponse;
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        }
    }
}
